程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

Selenium Webdriver Java 验证名称字段

发布于2022-12-05 23:34     阅读(171)     评论(0)     点赞(6)     收藏(5)


我对硒不是很有经验。我想通过执行以下操作来测试我的知识,验证表单中的名称字段没有特殊字符。我无法这样做。1st 我试图将字符放入数组中并从数组中读取,但我一直收到警报失败消息。然后我想到了以下方式并且总是让输出“有效”。

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

}


解决方案


您可以修复您的正则表达式以匹配任何非字母数字字符并使用PatternandMatcher代替:

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


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/583882/7900646f3668e8dd0aaa/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

6 0
收藏该文
已收藏

评论内容:(最多支持255个字符)