-1

我遇到的问题是我想在我的表单中创建一个与我的 html5 模式属性一起使用的 javascript 代码。

模式本身说明第一个字母必须是大写字母,最多 12 个字符。这就是我到目前为止所拥有的。感谢 Juhana,我得到了更好的模式代码。

^[A-Z][A-Za-z]{0,11}$

javascript 应该立即在屏幕上告知该人在输入字段时出错,并准确说明错误所在。我根本没有这方面的代码,因为我什至不知道如何使它与模式规则一起工作。

我已经坚持了一个星期了,我无法弄清楚。

先感谢您。

4

1 回答 1

0

The only opportunity to identify the error in a given string I see at the moment Is the following: You have to break up your regex and loop over the string.

Since your regex is fairly easy, you can start with ^[A-Z] to check if the first Symbol mathces a letter.

After that you go like this:

function check(string){

    var error = false,
        position = -1;

    loop : for(i=1;i<string.length;i++){
        var res = string.substring(i,i+1).match(/[A-Za-z]/);
        if(!res){
             position = i+1;
             error = true;
             break loop;
        }
    }
    return {'error':error,'position':position};
}


var check = check("aasfcd");

if (check.error){
    document.write("Error occured on position: "+check.position);
}else{
    document.write("Your string is okay");
}

​

See example fiddle

于 2012-04-23T07:25:11.517 回答