最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I validate a text box, which should only allow characters A-Z & a-z, not integers nor special chara

programmeradmin2浏览0评论

How to validate a text box in html, where user will enter his first name, and input do not accept integers & Special Characters?

<input name="txtfname" type="text" maxlength="30" required />

How to validate a text box in html, where user will enter his first name, and input do not accept integers & Special Characters?

<input name="txtfname" type="text" maxlength="30" required />
Share Improve this question edited Sep 2, 2014 at 9:50 SuperDJ 7,67111 gold badges43 silver badges78 bronze badges asked Sep 2, 2014 at 9:46 khan gggkhan ggg 11 gold badge1 silver badge2 bronze badges 5
  • <input name="txtfname" type="text" maxlength="30" required /> – khan ggg Commented Sep 2, 2014 at 9:47
  • With HTML pattern attribute, JS form validation or PHP $_POST validation ? There is a lot of way to do it and you tagged everything ... – Clément Malet Commented Sep 2, 2014 at 9:48
  • (Aside: What if my first name is André?) – RichieHindle Commented Sep 2, 2014 at 9:49
  • <input name="txtfname" type="text" maxlength="30" pattern="[a-zA-Z\s]+"/> – Trone Commented Sep 2, 2014 at 9:50
  • thanx,,, and to allow integers only which pattern will be mentioned in txt box. – khan ggg Commented Sep 2, 2014 at 9:52
Add a ment  | 

4 Answers 4

Reset to default 3

Try this javascript code for validation

function Validate() 
{
    var val = document.getElementById('your_input_control_id').value;

    if (!val.match(/^[a-zA-Z]+$/)) 
    {
        alert('Only alphabets are allowed');
        return false;
    }

    return true;
}

You will want to check the username field on both the client and server side.

Javascript:

var username = document.getElementsByName("txtfname")[0].value;
if (username .match(/^[A-Za-z]+$/)) {
    // Valid
} else {
    // Invalid
}

PHP:

$username = $_POST['txtfname'];
if (preg_match("/^[A-Za-z]+$/", $username ) {
    // Valid
} else {
    // Invalid
}
  In Javascript 
  var uname = document.form.username;   
   function validate(){
    var letters = /^[A-Za-z]+$/;  
    if(uname.value.match(letters))  
    {  
    return true;  
    }  
    else  
    {  
    alert('Username must have alphabet characters only');  
    return false;  
    }  
    }
    In Html 
    <form method="post" action="#" onSubmit="return validate();" name="form">
    <input type="text" name="username" class="username"/>
    <input type="submit" value="submit">
    </form>

This is the proper RegEx.

The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. This RegEx will also work for names like André.

^[\p{L} .'-]+$

var username = document.getElementsById("fname").value;
if (username .match(/^[\p{L} \.'\-]+$/)) {
    // Valid username
} else {
    // Invalid username
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论