Selenium Webdriver Java验证名称字段

时间:2016-05-01 23:39:43

标签: java selenium character

我对Selenium不太熟悉。我想通过执行以下操作来测试我的知识,验证表单中的名称字段没有特殊字符。我无法这样做。 1我尝试将字符放在一个数组中并从数组中读取但我一直收到警报失败消息。然后我想到了以下方式并始终将输出“有效”。

import 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#,@ 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");
    }
}

}

4 个答案:

答案 0 :(得分:1)

您可以修复正则表达式以匹配任何非字母数字字符,然后使用PatternMatcher代替:

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");
}

答案 1 :(得分:1)

我为验证名称字段所做的工作我使用了与开发人员在网站中使用的正则表达式相同的正则表达式。在我的情况下,名称字段仅接受字母数字字符。首先,我创建了一个Java函数,以随机生成带有特殊字符的字母数字,如下所示,然后将这种自动生成的输入与实际的正则表达式进行比较。由于在我的情况下不允许使用特殊字符,因此if语句将返回false,否则将执行块显示不允许使用特殊字符。

//can also be used for complex passwords
public String randomSpecial(int count)
{
    String characters = "~`!@#$%^&*()-_=+[{]}\\|;:\'\",<.>/?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    String generatedString = RandomStringUtils.random(count, characters);
    return generatedString;
}



public void TC_05_regExpression_Invalid()
    {
        String regex = "/^[a-zA-Z0-9- ]*$/";

    WebElement element = driver.findElement(By.name("firstName"));

        element.sendKeys(randomSpecial(10));
        String fieldText = element.getAttribute("value");

        if(fieldText.matches("["+ regex + "]+"))
        {
            logger.info("Valid Input: " + fieldText);

        }
        else
        {
            logger.info("InValid Input: " + fieldText + "not allowed");
        }

        element.clear();

    }

答案 2 :(得分: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

答案 3 :(得分: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);





}

}