Would like to know how to only accept number to be entered into inputbox from 1 to 9 and if entered for example 0 give alert message, sorry not a valid number.
please check my function that i have done so far, but not working.. thank you
<input name="number1" type="text" size="1" id="number1"onkeyup="doKeyUpValidation(this)/>
doKeyUpValidation(text){
var validationRegex = RegExp(/[-0-9]+/, "g");
if(!validationRegex.match(text.value)
{
alert('Please enter only numbers.');
}
You're missing a closing quote at the end of your onkeyup attribute, and as David mentions, you need to change your regex string to /[1-9]/
You were pretty close. Try this:
function doKeyUpValidation(text) {
var validationRegex = RegExp(/[1-9]+/, "g"); // The regex was wrong
if( !validationRegex.match(text.value) )
{
alert('Please enter only numbers.');
}
} // this was missing before
Your HTML is slightly wrong, it should be:
<input name="number1" type="text" size="1" id="number1" onkeyup="doKeyUpValidation(this)"/>
You need a space between each attribute, and each attribute needs to be quoted.
Also, your JavaScript has a few errors. It should be:
function doKeyUpValidation(text) {
var validationRegex = /[1-9]/g;
if (!validationRegex.test(text.value)) {
alert('Please enter only numbers.');
}
}
You need the function keyword to make doKeyUpValidation a function. Also, your regex was a little off.
Demo: http://jsfiddle.net/EqhSS/10/
Related
I have a form where you must enter a username, but the username cannot start or end with a period (.). This is what I have so far, I feel like I'm close. I think I am making an error in the .value[0] parts.
//Checking Username
if (document.getElementById("uName").value[0] == "." || document.getElementById("uName").value[-1]) {
document.getElementById("notification4").innterHTML ="Cannot have period at start or end.";
submitForm = false;
} else {
document.getElementById("notification4").innerHTML="";
}
My second question is how would I be able to stop the same character from repeating twice in a row? For example you can't have (--) , (//), (%%), (**) etc. I would prefer a similar method to use like above or with regex.
This is the forms HTML:
<label for="uName"> Username: </label><br>
<input type="text" id="uName" name="uName"> <br>
<div class= "error" id="notification4"></div><br>
You can use regular expression and the RegExp.prototype.test() function:
const regex = /^[.]|[.]$|[^a-zA-Z0-9]{2}/g;
if(regex.test(str)) {
//code when it matches
} else {
//code when it doesn't match
}
This checks if the first or last character is a dot (^[.]|[.]$) and if there is any character repeated twice that is not a letter or number ([^a-zA-Z0-9]{2}).
So I know how to do the remove/add class/attribute from a submit button, but I need to be able to apply this to a button based off of entry into an input.
The scenario is this, user enters their email address, but if it's at a specific domain, ex: xxxx#troopers.gov I then want to be able to apply/remove the class, and attribute from the submit button, since this is a domain they are not supposed to enter for a registration.
I have done some similar validation in the past, and tried a few different methods in jQuery .val(), indexOf, etc. But still can't seem to get it working.
I tried something like
var badDomain = 'troopers.gov';
and then
if (!$('#input').val() === badDomain) {
doStuff();
}
but it didn't seem to get me anywhere.
I thought I may be able to do this without using a RegEx (I don't have much experience with that)
Would be nice to be able to account for case as well... and I don't mind if the solution is jQuery, or pure JS... for learning purposes, it would be great to see how I could do it both ways...
So this does what you want, by turning anything typed into the field in lower case and then comparing against a given array of bad strings. Any time the input field blurs, it checks and turns the submit on or off.
Take a look in the code to see some bad addresses for sample use.
var badDomains = [
"troppers.com",
"fooBarBaz.org",
"myReallyUselessDomainName.com",
"a.net"
]
$(function(){
$("#email").on("blur", function(){
var addressBad = false;
var thisEmail = $(this).val().toLowerCase();
for (var i=0; i<badDomains.length; i++){
if (thisEmail.includes(badDomains[i])){
addressBad = true;
}
}
if (addressBad) {
console.log("bad address!")
$(".disabledButton").attr('disabled', "disabled");
} else {
console.log("not a bad address!");
$(".disabledButton").removeAttr("disabled");
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="email">Email:</label>
<input type="text" name="email" id="email" />
<input class="disabledButton" type="submit" disabled />
</form>
simple workaround :
var email = document.getElementById('email');
var checkEmail = document.getElementById('checkEmail');
checkEmail.onclick = function() {
if ((email.value).includes('#troopers.gov')) alert('This email address cannot be used!');
}
<input id="email">
<button id="checkEmail">Check Email</button>
there are multiple ways around though.
You can use a regex for this purpose.
HTML:
<input type="text" id="InputTest" />
<button id="TestBtn" type="button">
Validate
</button>
<p>
Valid
</p>
CSS:
.valid{
background-color:green;
}
.invalid{
background-color: red;
}
JS:
$("#TestBtn").on("click",function() {
var pattern = /\S+#troopers\.com/gi;
var str = $("#InputTest").val();
var arr = str.match(pattern);
alert(arr); // just to see the value
if(arr !== null){
$("p").addClass("invalid");
}
else{
$("p").addClass("valid");
}
});
Here is a JSFiddle. Basically, if what the user typed in the textbox matches the expression.. then the background color turns red, but if it doesn't match, then the background color turns green.
Let me know if this helps.
You can use the following Regex for the Email property of the related Model in order to accept mails having 'abc.com' suffix:
[RegularExpression("^[a-zA-Z0-9_#./#&+-]+(\\.[a-zA-Z0-9_#./#&+-]+)*#abc.com$",
ErrorMessage = "Please enter an email with 'abc.com' suffix")]
When working with a JavaScript function I want to prevent characters from being entered into a form if they do not meet certain parameters. The original JavaScript code I used was:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
That function worked while I was using only 1 input point in my form, however when I tried to use that function over multiple inputs it would only affect the first one in the form.
When creating a function that could be reused by multiple input boxes I got the following code:
function validateLetter(dataEntry){
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
}
catch(InputError) {
window.alert(InputError)
return false;
}
return true;
}
The form I am using to input information is:
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the city you were born in:
<input type="text" id="letter" name="letter" onkeypress="validateLetter();" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter" name="letter" onkeypress="validateLetter()">
</p>
</form>
Does anyone know a way to translate the last line of the first function: document.getElementById("letter").value = replacedInput;
To something that can be re-used with the current code.
I tried:
dataEntry.value = replacedInput
But that did not seem to run/change the function at all
The problem is in textInput.replace() - you forgot the second parameter. So instead of textInput.replace(/[^A-Za-z]/g);, you need textInput.replace(/[^A-Za-z]/g, "");.
As noted in the MDN website:
The ID must be unique in a document, and is often used to retrieve the element using getElementById.
In your example above, you are using the same value for the ID attribute on all of the input fields. Also, the name attribute should be unique within forms. The answer provided here explains in greater depth. With that said, in the examples below I have modified your input fields in respect to the above.
First off, the initial function you provided was pretty close. One issue with it is that the replace() method would need a second parameter. This parameter can be a string or a function to be called for each match. In your case I believe you just want an empty string:
function validateLetter() {
var textInput = document.getElementById("letter").value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
document.getElementById("letter").value = replacedInput;
}
Secondly, you can reference the current input field that is invoking validateLetter() by passing it along to the function as a parameter using the keyword this.
onkeypress="validateLetter(this);"
On a sidenote: You might achieve a better user experience using onkeyup instead of onkeypress. The example below utilizes this event instead so you can compare and judge for yourself.
Here is everything put together in a working example:
function validateLetter(target) {
var textInput = target.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g, "");
if(textInput != replacedInput)
alert("You can only enter letters into this field.");
target.value = replacedInput;
}
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded">
<p>Enter your mother's maiden name:
<input type="text" id="maiden" name="maiden" onkeyup="validateLetter(this);" />
</p>
<p>Enter the city you were born in:
<input type="text" id="city" name="city" onkeyup="validateLetter(this);" />
</p>
<p>Enter the street you grew up on:
<input type="text" id="street" name="street" onkeyup="validateLetter(this)">
</p>
</form>
How can I validate the following textarea using a pure Javascript not Jquery? Can anyone help me please.
<script>
function val()
{
// 1. only allowed alphanumeric characters, dash(-), comma(,) and no space
// 2. alert if person is trying to input not allowed chars as in 1.
}
</script>
<form>
<textarea name="pt_text" rows="8" cols="8" class="input" onkeydown="return val();"></textarea>
</form>
Try something like:
document.querySelector('.input').onkeypress = function validate(e) {
if (String.fromCharCode(e.keyCode).match(/[\w,-]/) == null) {
alert('not allowed');
e.preventDefault();
}
};
DEMO
Edit: As pointed out by tenub, \w also allows _, so modify the regex to: /[A-Za-z0-9,-]/
DEMO
This regex will match only valid strings:
/^[\w,-]*$/
Use + instead of * if you don't allow empty strings.
So I have a textbox which allows a max entry of 5 characters.
The user should enter the time in the format hh:mm or hhmm , into the textbox.
Supposing the user enters 1:2:3 or 1::2 etc, then it should show an alert message('Incorrect time format')
Is there any way I can check all other occurences of : EXCEPT for the first : , and alert the user?
(This needs to be done within a javascript function)
This is what I used to check for non-digit values(excluding :) entered into textbox:
<script type='text/javascript'>
function getClks(){
...
var re=":";
var found = clks.match(re);
if (clks.match(/^[0-9:]/)){
alert('Invalid time value');
}
if (found=:){
var splitime = clks.split(":");
var hours = splitime[0];
var mins = splitime[1];
......
}
}
</script>
Unless you have a very good reason to change the user's input. I would recommend only alerting the user that their input doesn't match the correct format.
If you really want to remove characters, you can use the replace function with some regex to remove the extra : chars.
You can use search or match to test whether the input is in the correct format.
Something like /^\d{1,2}:\d{2}$/ should work.
try to use this jquery plugin: http://digitalbush.com/projects/masked-input-plugin/
It will mask your textbox:
$("#hour").mask("99:99");
#alexl's jQuery plugin is probably enough, but for completeness sake..
Outside jQuery contexts I'd use a RegExp, /([0-9][0-9]):([0-9][0-9])/, and test the number string like so:
var timestr = /* .. get the text .. */
if(timestr.match(/([0-9][0-9]):([0-9][0-9])/) {
console.log('Good number string');
} else {
console.log('Bad number string');
}
Everyone else explained what to do. Here's a more concrete example of how to use it.
var regex = new RegExp("\\d{2}[:]\\d{2}");
if (regex.test(input)) {
var array = input.split(":");
var hours = array[0];
var minutes = array[1];
} else {
alert("malformed input");
}
You could do something like this
markup
<input id="myinput" maxlength="5" type="text" />
<input type="button" onclick="test()" value="test" id="testbtn" />
js
var re = new RegExp("^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$");
var myInput = document.getElementById('myinput');
function test(){
alert(re.test(myInput.value)); //alerts true if the input is well-formed
}
example => http://jsfiddle.net/steweb/rRZLx/