仅使用charectors对字母数字开始的Javascript验证,允许所有特殊的charectors但不允许启动空格 [英] Javascript validation for alphanumeric start with only charectors, allow all special charectors but not allow starting white space

查看:94
本文介绍了仅使用charectors对字母数字开始的Javascript验证,允许所有特殊的charectors但不允许启动空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅使用charectors的字母数字开始的Javascript验证,允许所有特殊的charectors但不允许启动空格。考试:



(考试12) - 允许

(test12) - 允许

(测试) - 允许

(12) - 允许

(test12) - 不允许(不允许以空格开头)

(test12 $%^#@ ) - 允许等..

解决方案

%^#@) - 允许等..


使用正则表达式,正则表达式适合你的目的是:

 ^ [a-zA-Z0-9] \。?



^ [ a-zA-Z]的意思是从任何字母数字小或首都开始

\。是指'包括数字和特殊字符在内的任何字符'

?表示零或更多



了解有关 Regex 在javascript中使用它的示例 [ ^ ]。



请尝试下面的示例代码:< br $> b $ b

 <   script  >  
function validate(){
var regex = / ^ [a-zA-Z0-9] \。 ?/ //正则表达式
if(document.myform.myinput.value.search(regex)== - 1)
{//如果匹配失败
alert(请输入有效输入。)
} else {//如果匹配传递
alert(谢谢你。)
}
}
< / script >

< form name = myform >
< 输入 type = text 名称 = myinput size = 15 >
< 输入 type = 按钮 onClick = validate() value = check >

< / form >



我在pettern下方使用,这将满足我的要求。

var patren = / ^ [a-z0-9] + [a-z0-9] \。?/ ;

Javascript validation for alphanumeric start with only charectors, allow all special charectors but not allow starting white space. Exam:

(test 12) - allow
(test12) - allow
(test) - allow
(12) - allow
( test12) - not allow (starting with white space not allowed)
(test12$%^#@) - allow etc..

解决方案

%^#@) - allow etc..


Use Regex, the regex that fits your purpose is:

^[a-zA-Z0-9]\.?


^[a-zA-Z] means 'start with any alphanumeric small or capital'
\. means 'any character including number and special characters'
? means 'zero or more'

Learn more about Regex and an Example to use it in javascript[^].

Try my sample code below:

<script>
function validate(){
var regex=/^[a-zA-Z0-9]\.?/ //regular expression
if (document.myform.myinput.value.search(regex)==-1)
{ //if match failed
alert("Please enter a valid input.")
} else { // if match passed
alert("Thank you.")
}
}
</script>

<form name="myform">
<input type="text" name="myinput" size=15>
<input type="button" onClick="validate()" value="check">

</form>


Hi,
I am using below pettern and this will fulfill my requirement.
var patren=/^[a-z0-9]+[ a-z0-9]\.?/;


这篇关于仅使用charectors对字母数字开始的Javascript验证,允许所有特殊的charectors但不允许启动空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆