I'm trying to wrap my head around RegExp. I currently have a form where I want to validate that the user input is only letters, (although an example of letter and number and spaces would be helpful to). I want this validation to be checked from a submit button. Can anyone help me out with my syntax/logic? Also please explain your answer so I can try to understand it. I'd also like to keep it in just JavaScript if possible, Any help in this matter would be greatly appreciated!
here is my form's code:
First name: <input type="text" name="firstName" /><br />
<span id="firstNameWarnings" style="color:black"> </span>
<button type="submit" onclick="return validateRegistrationForm()" >Register</button>
Note: My JavaScript runs all functions through master function. (submit calls the master function.)
here is my current JavaScript code:
function validateFirstName()
{
var k=document.forms["registration"]["firstName"].value;
var vld=new RegExp([A-Za-z]);
if( k != vld)
{
document.getElementById("firstNameWarnings").style.color = "#F00";
document.getElementById("firstNameWarnings").innerHTML = "First name onyl take letters!";
return false;
}
else
{
document.getElementById("firstNameWarnings").innerHTML = "";
return true;
}
}
Use the test method in RegExp
if( vld.test(vk))
Here's more info on the RegExp test method.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/test
You can use this for check - if (/^[a-zA-Z]+$/.test(k)).
^ - matches at the start of the string.
[a-zA-Z] - any character from range.
+ - one or more times.
$ - matches at the end of the string.
Related
I need to make a calculator using JavaScript, HTML and CSS. Everything worked out fine until I came to coding the compute (=) button.
This is my HTML:
<input type="button" value=" = " onclick="compute()">
This is my JS:
function compute() {
var input_var = document.getElementById('input');
ans = Math.floor(+eval(input_var.value));
document.getElementById('answer').value = '=' + 'ans';
}
If anyone that knows how to solve what's wrong, I would greatly appreciate it if you could reply.
First of all, you should post the whole code to get accurate solution!
Probably these could be some of the errors:
Set id attribute of your = button with value "input"
3rd line should be: ans = Math.floor(eval(+input_var.value));
4th line should be: document.getElementById('answer').value = '=' + ans; as StaticBeagle has also mentioned.
You should be lucky that you made the mistake to put the variable in quotes. That's why you don't get a value other than the literal string =ans(maybe, we don't know as you didn't post all code that's needed to give a better answer).
Back to why you're lucky.
Never use eval! eval is evil. (Unless you know what you do, but you don't the next couple of years). To parse a number, you'd use Number(input_var.value).
The next error is that you create a global variable by omitting one of var, let, const for your ans declaration.
The next thing you shouldn't do is to use inline javascript. We use eventListener instead. As said before, it's impossible to answer more specific as your question lacks too many details - however I'll show you how you get a value by pressing a button in the console.
document.getElementById('foo').addEventListener('submit', e => {
// prevent submitting the form (I guess another error in your code)
e.preventDefault();
const value = Number(document.getElementById('input').value);
console.log('The value is: ' + value);
}, false);
<form id="foo">
<input type="number" id="input">
<input type="submit" value=" = ">
</form>
Not sure if ans is a local or global variable, but if its intention is to be a local variable then you should have it like this:
var ans = Math.floor(eval(+input_var.value));
Also, because you're setting the value of your element to '=' + 'ans' you're actually setting it to the actual string 'ans'. If you want to refer to what ans is you should write it like this:
document.getElementById('answer').value = '=' + ans;
I'm still learning about Regular expressions, still little bit confused using it.
My case :
I need block some specific word in input html with javascript or jquery.
Words i need to block is admin or administrator keyword, i don't want people using keyword like admin or administrator when create new account (username).
I need to block keywords like admin, 4dmin, adm1n, 4dm1n or even ADMIN, 4Dm1N..No matter user input in lowercase or uppercase or even numeric to replace letter "A" with numeric "4".
For now my code is :
var input = document.getElementById("inputUser");
input.onkeyup = function() {
input.value = input.value = input.value.replace(/(admin|4dmin|adm1n|4dm1n)/,"");
}
Please help dear masters, i'm stuck at this moment, any help i very appreciate.
You could write a regular expression without bars more easily by using character classes and the i flag (ignores casing):
input.value = input.value.replace(/[a4]dm[i1]n/ig, '');
Make sure to only use a single = - your current code duplicates input.value = input.value =.
But do keep in mind that you shouldn't be relying on Javascript alone to manage this - also verify the input before putting it in the database.
You can try this using regex
^(?!.*admin|.*4dmin|.*4dm1n).*$
You can keep an array of blacklisted words and onkeyup check if the value matches with any word in that array
var input = document.getElementById("inputUser");
var restrictedVal = ["admin", "4dmin", "adm1n", "4dm1n"]
input.onkeyup = function() {
if (restrictedVal.indexOf(input.value.toLowerCase()) !== -1) {
input.value = "";
}
}
<input type="text" id="inputUser">
I am trying to take a string entered by user from a textbox. Check the length of that string and if the string is over a given number perform the slice operation on it.
Here's what I came up with but my code does nothing. Checked console, no errors given.
html:
<form id="slice">
Enter a pharse:<input type="text" id="text_box_2"><br>
<input type="button" value="slice" onclick="Slice()">
Result: <input type="text" id="slice_result"><br>
</form>
Javascript function:
function Slice(){
var UserString = document.getElementById("text_box_2").value;
var UserStringValue = UserString.length;
var Result = Userstring.slice(1,6);
if (UserStringValue > 6){
document.getElementById("Slice_result").value = Result;
}
else{
alert("Please enter a longer phrase.")
}
}
what or where did I go wrong?
Be mindful of case-sensitivity.
This:
var Result = Userstring.slice(1,6);
Should be using UserString (capital "S") as defined earlier in your code.
Next, the input ID should be all lowercase, slice_result, to match to HTML, but your code uses different casing:
document.getElementById("Slice_result")
Here's a working JSBin with these fixes.
EDIT: As JaromandaX mentioned in the comments, if you want to take the first 6 characters you should use slice(0, 6).
from cursory reading of your code. it seems caused by this line
var Result = Userstring.slice(1,6);
and also this one
document.getElementById("Slice_result").value = Result
it should be
var Result = UserString.slice(1,6);
and
document.getElementById("slice_result").value = Result
Usually use of the following
var Value = $('#input_id').val();
will pull the requested information for you.
You can also set up arguments for your slice function and pass in the value when you run onclick();
I'd also note that slice() is a current js function, though your implentation with the capital 'S' is some what different, it may be better practice to change that name a bit.
So I'm using the minimal regex [0-9]* for the iPhone number pad in my HTML5 pattern attributes. I also had a submit function that sends an email through the server. Everything was working good until I realized it was trying to send the form re3gardless of whether the browser was trying to block submit based on incorrect user input.
So I did the following but can't get it to work:
<script>
function validate(){
var phone=/[0-9]*/;
var x=document.forms["form"]["contactnum"].value;
if (x!=phone){
alert("Contact Number must be a valid phone number (no dashes)");
return false;
}
else {
alert("Thank you! We have received your information and will contact you shortly.");
ajax('{{=URL('new_post')}}',['phone'], 'target');
return false;
}
}
</script>
The problem is I can only get it to work if I set if (x==null || x=="") in the if statement. If I try to match it with any other var it will always say I'm not matching the [0-9]*. I already have written several complex regex's but really don't want to use anything on this simple form. I just wanted the number pad on the iPhone and not to submit if it wasn't a digit or null. I don't even care if they put in a "2" for the phone, just so long as it's a digit.
Thanks.
if ( x.match(/^[0-9]+$/) ) {
// valid
} else {
// invalid
}
That's not how you use a regular expression:
if (!phone.test(x)) ...
Also if you want to match a string with nothing but digits, try
var phone = /^\d*$/;
That will match the empty string too; use + instead of * if you want at least one digit.
You actually seem to have two questions in one here. For the first part, you haven't shown how you're using validate(), but remember that the onsubmit handler, itself, must return false to keep the browser from completing the normal submit process. For example, the following will not work:
$('#myform').submit(function(){
validate();
});
But this would successfully stop the default submit process:
$('#myform').submit(function(){
return validate();
});
validate() would return false, and then your handler returns the same.
I have asp:textbox I want to restrict the text box to allow only integer values.
How can I do that using javascript in asp.net.
If you use the replace function and some regualar expressions you will be able to do this.
<input type="text" name="textbox" onkeyup="integersOnly(this)">
<script type="text/javascript">
function integersOnly(obj) {
obj.value = obj.value.replace(/[^0-9-.]/g,'');
}
</script>
That will also keep in the decimal place.
If you just want integers use:
obj.value = obj.value.replace(/[^0-9]/g,'');
All this function is doing is taking what is input and removing any characters that are not numbers.
Alternatively you can do this in jQuery. If you use jQuery let me know and I will let you know how I do it.
EDIT
Following on from your comment you could use the following updated function:
var integer_only_warned = false;
function integersOnly(obj) {
var value_entered = obj.value;
if (!integer_only_warned) {
if (value_entered.indexOf(".") > -1) {
alert('Please enter an integer only. No decimal places.');
integer_only_warned = true;
obj.value = value_entered.replace(/[^0-9]/g,'');
}
}
obj.value = value_entered.replace(/[^0-9]/g,'');
}
What this is doing is first checking if a decimal has been entered. If it has then it is warning the user and then removing the decimal place. I have also added a check, so that the warning only comes up once every page load.
Hope that helps.
Use a RegularExpressionValidator control and set the EnableClientScript property to True.
Check this example.
Restrict Characters and Allow only Integers in Textbox using JavaScript
Just to throw this in too, if you happen to be using AJAX Control Toolkit, there is an extender already built that makes filtering content a snap: http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/FilteredTextBox/FilteredTextBox.aspx