2016-05-01 3 views
1

Я не очень опытен с Selenium. Я решил проверить свои знания, выполнив следующее: подтвердите, что поле имени в форме не имеет специального символа. Я не мог этого сделать. 1st Я попытался поместить символы в массив и прочитать из массива, но я продолжал получать сообщение об ошибке предупреждения. Затем я подумал о следующем способе и всегда получаю вывод «действительный».Selenium Webdriver Java validate name field

импорт junit.framework.Assert;

import org.openqa.selenium.Alert; 
import org.openqa.selenium.By; 
import org.openqa.selenium.NoAlertPresentException; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.testng.annotations.Test; 


public class NameField { 
    public static FirefoxDriver fx= new FirefoxDriver(); 
    public static String doCheck() 
    { 




     fx.get("http://www.gogamers.com/#!blank/gs4id"); 
     String regex = "^[A-Z0-9+$"; 

     String str=fx.findElement(By.id("comp-iikjotq8nameField")).getText(); 
     fx.findElement(By.id("comp-iikjotq8nameField")).sendKeys("@john"); 



     if (str.matches("[" + regex + "]+")){ 
      System.out.println("Invalid character in Name field"); 
     } 
     else{ 
      System.out.println("valid"); 
     } 
     return str; 

То, что я имею в виду, если вы даете имя с помощью SendKey (например: Джон #, @John) вы получите недопустимое сообщение. Еще одна вещь, о которой я думал, следует использовать утверждение? Пожалуйста, предложите лучший способ использования небольшого примера кода.

Новый код, который я пробовал сегодня, который все еще дает мне Действительный, когда я ожидаю, что недействителен. Может кто-нибудь любезно взглянуть, пожалуйста? Я попробовал оба матча и найти

общественного класса Yahoomail {

public static void main(String[] args) { 

    FirefoxDriver fx= new FirefoxDriver(); 
    fx.get("https://login.yahoo.com/account/create?"); 

    String title=fx.getTitle(); 
    Assert.assertTrue(title.contains("Yahoo")); 
    //First I send a text, then I get the text 
    fx.findElement(By.id("usernamereg-firstName")).sendKeys("$John"); 

    fx.findElement(By.id("usernamereg-firstName")).getText(); 

    //This is the String I want to find 
    String firstName="John"; 

    //If there are these symbols associated with the name-show invalid 
    String patternString = ".*$%^#:.*"; 

    Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); 
    Matcher matcher = pattern.matcher(firstName); 
    if(matcher.find()){ 

     System.out.println("Invalid Name"); 
    } 
    else{ 
     System.out.println("Valid Name"); 
    } 
} 

}

ответ

1

Вы можете установить регулярное выражение, чтобы соответствовать любые не алфавитно-цифровые символы и использовать Pattern и Matcher вместо:

Pattern p = Pattern.compile("\\W"); 
Matcher m = p.matcher(str); 
if (m.find()) { 
    System.out.println("Invalid character in Name field"); 
} 
else { 
    System.out.println("valid"); 
} 
0

Сейчас он работает, проблема в том, что я не был захвачен значение sendKeys. Я должен был использовать GetAttribute

f.get("https://mail.yahoo.com"); 
     f.findElement(By.id("login-username")).sendKeys("jj%jo.com"); 


     //The getAttribute method returns the value of an attribute of an HTML Tag; 
     //for example if I have an input like this: 
     WebElement element = f.findElement(By.id("login-username")); 
     String text = element.getAttribute("value"); 
     System.out.println(text); 

if((text).contains("@")){ 
    System.out.println("pass"); 
} 
else{ 
    System.out.println("not pass"); 
} 


    enter code here 
0
public class Personal_loan { 

public String verified_number(String inputNumber) // pass the parameter 
{ 
    String validation; 

    String regexNum = "[0-9]+";   //"[A-Za-z]";//"^[A-Z+$]"; 

    if (inputNumber.matches("[" + regexNum + "]+")) 
    { 
     System.out.println("valid"); 
     validation="valid"; 
    } 
    else{ 

     System.out.println("Invalid character in Name field"); 
     validation="invalid"; 
    } 
    return validation; 

} 

public String verified_str(String inputStr) 
{ 
    String regexString = "[A-Za-z]";//"^[A-Z+$]"; 

    if (inputStr.matches("[" + regexString + "]+")) 
    { 
     System.out.println("valid"); 
    } 
    else{ 

     System.out.println("Invalid character in Name field"); 
    } 
    return null; 

} 



public static void main(String[] args) { 


    System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe"); 
    WebDriver driver = new ChromeDriver(); 
    driver.get("https://www.iservefinancial.com/"); 
    driver.findElement(By.xpath("(//DIV[@itemprop='name'])[1]")).click(); 
    WebElement LoanAmount =driver.findElement(By.xpath("//INPUT[@id='amount_qa']")); 
    WebElement Income =driver.findElement(By.xpath("//INPUT[@id='income_qa']")); 
    LoanAmount.sendKeys("12345"); 
    Income.sendKeys("amount"); 

    Personal_loan pl=new Personal_loan(); //creating object 


    String g = LoanAmount.getAttribute("value"); // store the value in string 
    String incomevalue = Income.getAttribute("value"); 


    String lavalid=pl.verified_number(g); 
    String income_valid = pl.verified_number(incomevalue); 


    System.out.println("Loan Amount "+lavalid); 
    System.out.println("income Amount "+income_valid); 





} 

}

+0

Обычно это лучше объяснить решение, а не просто размещение некоторых строк анонимного кода. Вы можете прочитать [Как написать хороший ответ] (https://stackoverflow.com/help/how-to-answer), а также [Объяснение полностью основанных на кодах ответов] (https://meta.stackexchange.com/вопросы/114762/объяснения-entirely-% E2% 80% 8C% E2% 80% 8Bcode на основе-ответы) –

Смежные вопросы