I am trying to validate a user entered password. It can only be letters and numbers and I have to use the match method...even if it isn't the best way...I have to use match(). I am missing something to get the working properly. No number or special characters only letters. I do not know much about javascript.
<script type="text/JavaScript">
function chkPwd() {
var pwd = document.form1.pwd;
var pwdMsg = document.getElementById('pwdMsg');
regex = /[^a-zA-Z]/;
var pwd1 = pwd.value;
if(!pwd1.match(regex)) {
pwdMsg.innerHTML = "Must contain letters only!"
pwd.select();
return;
}else{
pwdMsg.innerHTML = "";
}
}
</script>
</head>
<body>
<form name="form1" action="" method="post">
<p> Password: <br>
<input type="text" name="pwd" onchange="chkPwd()" />
<span id="pwdMsg"></span></p>
<p>
<input type="button" value="chkPass" onclick="chkPwd()">
</p>
</form>
<div id="results"></div>
</body>
</html>
Your issue appears to be in this section of code.
regex = /[^a-zA-Z]/;
var pwd1 = pwd.value;
if(!pwd1.value.match(regx)) {
You are setting the pwd1 to pwd.value, but then on the next line, you are accessing pwd1.value. This means that you are efficiently doing pwd.value.value. Additionally, you are using regx where you should use regex. Also, your if condition does not appear to need a ! in it. I think you mean to do this.
regex = /[^a-zA-Z]/;
var pwd1 = pwd.value;
if(pwd1.match(regex)) {
If you want letters only you should use this regex:
^[A-Za-z]+$
If you want to have letters and numbers then use:
^[A-Za-z0-9]+$
Btw, as guys pointed out you are using regx instead of regex
Related
Create an html page with the following form:
<form method="post" name="example" action="">
<p> Enter your name <input type="text"> </p>
<input type="submit" value="Submit Information" />
</form>
<div id="a"></div>
Add a js validation function to the form that ensures that you can only add numbers in the textbox If you enter alphabets, you should generate an error message in the given div. -->
I run the requirement successfully and I'm giving the error message when it entered alphabets. However, it's giving me the same error message when I enter digits as well. Please kindly show how the function or the window.onload should be implemented. Thank you.
My answer is down below;
window.onload = function() {
let form = document.getElementById('form_ref')
form.onsubmit = function() {
let user = form.user.value;
if (parseInt(user) !== user) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
return true;
}
}
<form id="form_ref" method="post" name="example" action="">
<label for="username">User</label><input type="text" name="user" id="username" required>
<div id="a"></div>
<br>
<input type="submit" value="Submit Information" id="submit">
</form>
Your equality check parseInt(user) !== user will always return true because form.user.value is a string but parseInt(...) always returns an integer. If you want to check if the entry is an integer there are a couple ways.
You can change the input's type attribute to number to make sure only digits can be entered and then you just have to make sure it's an integer and not a decimal (type="number" still allows decimal numbers so not just digits). user will still be a string, but it's easier to check. I'd recommend using Number.isInteger(...) to do the checking:
if (!Number.isInteger(parseFloat(user))) {
If you really want to use type="text" you can iterate through user and make sure its characters are all digits:
for(let i = 0; i < user.length; i++) {
if("0123456789".indexOf(user[i]) == -1) {
document.querySelector('div').innerHTML = "Error! Please enter digits only!";
return false;
}
}
return true;
One advantage of this method is that you can make more characters available if you want to just by adding them to the string that's searched in the iteration. A disadvantage is that it's slower than the other method (the indexOf method has to iterate through the string for every character of user), but for your use case that seems irrelevant-- this function doesn't need to be called many times per second as it's a simple login type of thing, and it's client-side so you don't need to handle many instances at once. If speed is an issue you could probably make a comparison to the integer equivalencies of the characters:
if(user.charCodeAt(i) < "0".charCodeAt(0) || user.charCodeAt(i) > "9".charCodeAt(0)) {
I want to block some special characters from entering in text box.
`~ #$^+|\ []{}<> these are the characters i would like to prevent from user inputting. Can any one suggest a solution or reg ex.
function some(){
var input = document.getElementById('one').value;
var one = input.replace(/[(\\^`~#\$\^\+\|\\\[\]{}<>)]/g,"");
document.getElementById('one').value=one;
}
<input type="text" oninput="some()" id="one" >
<input type="text" pattern="[^`~#\$\^\+\|\\\[\]{}<>]+">
I am finding a way to make all the text boxes in the website only accept roman characters. Is there any easy way to do it globally.
Thanks in advance.
In modern browsers <input> accepts an attribute called pattern. This allows to restrict the valid characters in a given field.
input:invalid {
background-color:red;
}
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
For all other browsers you can find all form field via jQuery, check if a pattern-attribute exists, and check it against the value of a given field. You may also replace disallowed characters:
$('form').on('keyup blur','input',function() {
if ($(this).val() && $(this).attr('pattern')) {
//var pattern = new RegExp('^'+$(this).attr('pattern')+'$', 'g');
//$(this).toggleClass('invalid', pattern.match(!$(this).val()));
var pattern = new RegExp($(this).attr('pattern').replace(/\[/,'[^'), 'g');
$(this).val($(this).val().replace(pattern,''));
}
});
input:invalid {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<input type="text" pattern="[a-zA-Z\s\.\-_]+" />
<button type="submit">Submit</button>
</form>
Oh, you still want to validate form inputs on the server-side. All HTML- or Javascript-stuff does not prevent all visitors of your site to submit broken stuff.
I will refer to the marked answer for the following question for the regex which filters out non-roman characters:
How to detect non-roman characters in JS?
Spoiler: the regex is /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g
Now all you need is a little bit of tinkering with jQuery:
var myInputId = "#foo"; // Or whatever you wish to use.
var input = $(myInputId);
var exp = /[^\u0000-\u024F\u1E00-\u1EFF\u2C60-\u2C7F\uA720-\uA7FF]/g;
input.blur(function() {
input.value = input.value.replace(exp, "");
});
Include this snippet into your master page for example:
<script>
$(function(){
$('input[type=text],textarea').keypress(function(e){
var char = String.fromCharCode(e.which || e.charCode);
var rgx = /[\u0000-\u007F]/;
if (rgx.test(char) == false)
return false;
})
})
</script>
Here is my idea based on #fboes answer.
I also needed to show user whats wrong, so there is error message showing but with no redundancy when typing couple of forbidden characters in a row.
//I wanted first to assign pattern attr to every input in form but when it's happening, all "\" chars are removed from regex therefore - it doesn't work, so I had to add it in templates for every input.
let isIncorrect = false;
scope.checkPattern = function(e) {
// I don't want to allow Chineese, cyrylic chars but some other special - yes
var pattern = new RegExp('[a-zA-Z\s\.\-_äÄöÖüÜßąćęłńóśźżĄĆĘŁŃÓŚŹŻ]+', "g");
if ($(e).is(':valid')){
return true
} else {
$(e).val($(e).val().replace(pattern,''));
return false
}
};
scope.removeAlert = function (e){
$(e).parent().find('.text-danger').remove();
isIncorrect = false;
}
// unallowed characters in order inputs
$('.my-form').on('keyup blur','input',function(e) {
if (!scope.checkPattern($(this))) {
if (!isIncorrect){
// show this error message but only once (!) and for specified period of time
$(this).parent().append('<p class="text-danger">Only latin characters allowed</p>');
isIncorrect = true;
}
setTimeout(scope.removeAlert, 3000, $(this));
}
});
HTML code:
<input id="lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_:services:dtServicesTable:0:_id68:0:framedRouteIp" name="lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_:services:dtServicesTable:0:_id68:0:framedRouteIp" value="10.9.9.9" class="" type="text">
JavaScript code:
var grade = $('#lfr\\_\\_WSRP\\_e044d147\\_\\_55a7\\_\\_4e6b\\_\\_9e5f\\_\\_938e05d9050c\\_\\:services:dtServicesTable\\:'+i+'\\:\\_id68\\:'+j+'\\:framedRouteIp').val();
but my JavaScript code is not giving me the value.
Should be like the following code since underscore _ is not a special character, you have just one special character : that you have to escape.
Hope this helps.
var i=0,j=0;
var grade = $('#lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_\\:services\\:dtServicesTable\\:'+i+'\\:_id68\\:'+j+'\\:framedRouteIp').val();
$('#result').text(grade);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_:services:dtServicesTable:0:_id68:0:framedRouteIp" name="lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_:services:dtServicesTable:0:_id68:0:framedRouteIp" value="10.9.9.9" class="" type="text">
<br>
<span id='result'></span>
Note : Check comments in question You should seriously reconsider whatever it is you're trying to accomplish with an input ID like that....
You should only escape : as _ is not a special character
So your javascript code will be :
var grade = $('#lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_\\:services\\:dtServicesTable\\:0\\:_id68\\:0\\:framedRouteIp').val();
this will work
use \\ before : only as your Id have : special character _ (underscore is not special character )
Run below code and check output in console.
<script src="//code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var grade = $("#lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_\\:services\\:dtServicesTable\\:0\\:_id68\\:0\\:framedRouteIp").val();
console.log(grade);
});
</script>
<input id="lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_:services:dtServicesTable:0:_id68:0:framedRouteIp" name="lfr__WSRP_e044d147__55a7__4e6b__9e5f__938e05d9050c_:services:dtServicesTable:0:_id68:0:framedRouteIp" value="10.9.9.9" class="" type="text">
I cannot understand where i am going wrong.
Simple Form.
<form name="myForm" method="post" action="" onsubmit="return(validate());">
<fieldset>
<label for="phone">Phone Number </label>
<input type="text" name="phone" size="30"><br><div id="badphone" style="background-color: #A9A9F5;"></div>
</fieldset>
</form>
<script>
function validate()
{
var pattern2=new RegExp("[/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/]");
if(document.myForm.phone.value.match(pattern2))
{
var badphone = "<strong>Phone Number can only contain Numbers 0-9</strong>";
document.getElementById("badphone").innerHTML = badphone;
document.myForm.phone.focus() ;
return false;
}
}
</script>
I have tried a couple other Regex's to get this to work but no luck.
I am tring to get an output like:
1112223333, 111-222-3333, (111)222-3333, 111 222 3333, 111.222.3333
Currently it is not validating at all.
Your syntax of using regex using RegExp constructor is wrong.
Your regex can be simplified to:
var pattern2 = /^\(?\d{3}\)?[-\s.]?\d{3}[-\s.]?\d{4}$/;
Why are you using the [/ and /] at the start and ending of the RegEx?
Try removing it.
If want to say not in JS try this
if(!document.myForm.phone.value.match(pattern2))
If the what you have is doing the opposite of what you want change the operator.