Regex for different classname form input - regex

This is the original code
$('.holder').on('keypress', 'alphabet', function (e) {
if (window.event) code = e.keyCode;
else code = e.which;
var myRegExp = new RegeExp(/[A-Z]/i);
if (myRegExp.test(String.fromCharCode(code))) {
return true;
} else return false;
});
however i want to make this code reusable as classname as parameter, like this one, but its not working :
$('.holder').on('keypress', classname, function (e) {
if (window.event) code = e.keyCode;
else code = e.which;
var pattern;
if (classname == "alphabet") pattern = /[A-Z]/i;
else if (classname == "number") pattern = /[0-9]/;
var myRegExp = new RegeExp(pattern);
if (myRegExp.test(String.fromCharCode(code))) {
return true;
} else return false;
});
see this FIDDLE

This should be your HTML. You should have a name attribute for an input element
<div class="holder">
alphabets only : <input type="text" name="name" class="alphabet" /><br />
numbers only : <input type="text" name="age" class="number" />
</div>
And this is the JavaScript. You need an event on input and not on holder and you don't need to pass classname as a parameter; rather check it with .attr('class')
$('input').on('keypress', function (e) {
if (window.event) code = e.keyCode;
else code = e.which;
var pattern;
if ($(this).attr('class') == "alphabet") pattern = /[A-Z]/i;
else if ($(this).attr('class') == "number") pattern = /[0-9]/;
var myRegExp = new RegExp(pattern);
if (myRegExp.test(String.fromCharCode(code))) {
return true;
} else return false;
});
Demo

on(...) does not define a function. It calls a function. You can't have an undefined variable there. Wrap the whole thing into a function.
Also, the second parameter to on(...) needs to be a selector, but "alphabet" would try to select a tag <alphabet>, which does not exist. The class selector is ".alphabet".
You also misspelled RegExp.
function applyKeypressValidation(selector, classname) {
$('.holder').on('keypress', selector, function (e) {
if (window.event) code = e.keyCode;
else code = e.which;
var pattern;
if (classname == "alphabet") pattern = /[A-Z]/i;
else if (classname == "number") pattern = /[0-9]/;
var myRegExp = new RegExp(pattern);
if (myRegExp.test(String.fromCharCode(code))) {
return true;
} else return false;
});
}
applyKeypressValidation('.alphabet', 'alphabet');
applyKeypressValidation('.number', 'number');

Related

Prevent user from entering numbers but keep the alphabetical characters they have already entered

I'm trying to stop user from entering numbers in an input form but keep alphabetical characters. At the moment,as soon as the user enters a number, my code erases everything entered before, e.g. "Ann3" turns to an "".
I don't know how to keep "Ann" when the user accidentally hits "3". This is what I've got so far:
updateName(event) {
var value = event.target.value;
var model = this.state;
if (!value.match("^[a-zA-Z]*$")) {
value = "";
};
this.setState({ [event.target.name]: value })
I wonder if I could use concatenation here, I'm sorry, I'm new to ReactJS and programming in general and don't know where to start.
Rather than setting value to the empty string, you could use .replace to replace all non-alphabetical characters with the empty string (thereby keeping alphabetical characters and their relative positions):
updateName(event) {
const { value, name } = event.target;
this.setState({ [name]: value.replace(/[^a-z]/gi, '') });
}
i did a code sample with react bootstrap but i'm sure it will work for you:
let { FormGroup,ControlLabel,FormControl } = ReactBootstrap;
class Example extends React.Component {
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
this.state = {
value: ''
};
}
getValidationState() {
const length = this.state.value.length;
if (length > 3) return 'success';
else if (length > 2) return 'warning';
else if (length > 0) return 'error';
return null;
}
handleChange(e) {
this.setState({value : e.target.value.replace(/[^a-z]/gi, '')})
}
render() {
return (
<form>
<FormGroup
controlId="formBasicText"
validationState={this.getValidationState()}
>
<ControlLabel>keep alphabetical characters</ControlLabel>
<FormControl
type="text"
value={this.state.value}
placeholder="Enter text"
onChange={this.handleChange}
/>
<FormControl.Feedback />
</FormGroup>
</form>
);
}
}
ReactDOM.render(
<Example />,
document.getElementById('app')
);
https://codepen.io/ene_salinas/pen/zmMyOb?editors=0010
Happy coding!

Finding text between tag <a> (regex with variable)

function Selection () {
if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
if (sel.rangeCount) {
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
var result = html.indexOf("href");
if (result != -1) {
window.getSelection().empty();
window.getSelection().removeAllRanges();
} else {
var textofclassText = $('.text').html();
//var patt1 = /id=\"load([\s\S]*?)+[selectedTexthtml]/g;
var result_2;
//var result_2 = textofclassText.search(patt1);
if(result_2 != "null") {
window.getSelection().empty();
window.getSelection().removeAllRanges();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div class="text" onmouseup="Selection()">
You
<br><a class="good" data-id="3" href="#load" id="load3">are very </a> important for us.
<br>So we're offering you
<br><a class="good" data-id="4" href="#load" id="load4"> win-win</a> option.
<br>You will get 2 refrigerators if you buy one
</div>
</body>
</html>
I need to remove selection if the selected text contains "a" tag. If I start to select link-text from left I will get only text "are very", so I need to find first match in all class ".text". I can't get how to use variable in that regex, because when I try to build string from variables it doesn't work.
var patt1 = new RegExp("id=\"load([\s\S]*?)" + html, "g");
var result = textofclassText.search(patt1);

ReactJS Simulate change value / unit testing

i try to simulate a test of a value change on my InputText component. I really don't know how to make that. I just know I must use the ref and the onChange method. But when I put a ref on my test I got an error like "you might be adding a ref to a component that was not created inside a component's render method".
Edit = I give a ref in the render of my InputText component
This is the render of my InputText component
render: function () {
console.log('passerender');
var attrs = this.generateAttributes();
var type = this.props.area ? "textarea" : "text";
return (
<Input
className={this.props.menuClassName}
type={type}
{...attrs}
{...this.props.evts}
className={this.props.menuClassName}
onChange = {this.handleChange}
onBlur = {this.handleBlur}
value={this.state.value}
ref = "InputField"
hasFeedback
/>
);
}
});
This is my test page of my InputText component:
var React = require('react'),
InputText = require('../resources/assets/js/testcomponents/InputText.js').InputTextEditable,
TestUtils = require('react-addons-test-utils'),
ReactDOM = require('react-dom');
describe('InputText', function () {
var InputElement = TestUtils.renderIntoDocument(
<InputText
area={false}
//evts={{onChange: handleChange}}
attributes={{
label:'Test Input Isole',
name:'InputTextArea',
value: '',
wrapperClassName: 'col-md-4',
labelClassName: 'col-md-2',
groupClassName: 'row'
}}
//ref="InputField"
editable={true}/>);
var DomElement = ReactDOM.findDOMNode(InputElement);
var inputV = ReactDOM.findDOMNode(InputElement.refs.InputField);
var input = DomElement.getElementsByTagName('input')[0];
var inputspan = DomElement.getElementsByTagName('span')[1];
it('updates input value on key press', function () {
inputV.value = 'test';
expect(input.getAttribute('value')).toEqual('');
TestUtils.Simulate.change(inputV);
TestUtils.Simulate.keyDown(inputV, {key: "Entrer", keyCode: 13, which: 13});
expect(input.getAttribute('value')).toEqual('test');
});
You can use findRenderedComponentWithType or findRenderedDOMComponentWithTag
You don't need to call findDOMNode explicitly, because TestUtils has done this for you.
var InputElement = TestUtils.renderIntoDocument(
<InputText {...yourProps}/>
);
// Assuming there is only one <input /> DOM element in your Input
var input = TestUtils.findRenderedComponentWithType(InputElement, Input)
// or you can just find <input /> directly
var input = TestUtils.findRenderedDOMComponentWithTag(InputElement, 'input');
TestUtils.Simulate.change(input);
TestUtils.Simulate.keyDown(input, {key: "Entrer", keyCode: 13, which: 13});
Ok I find the problem of the syntax error. It was on my html5validator on my input mixin. I put a try/catch to solve this :
var html5Validity = true;
if (DOM !== undefined) {
try {
html5Validity = $(DOM).find(':invalid').length == 0;
console.log('passe');
} catch (e) {
console.log('html5Validity = [catch]');
html5Validity = true;
}
}
attrs = _.extend({'data-valid': validation.isValid && html5Validity}, attrs);
Now it's OK ! Thank you ! :)

I'm flummoxed. In IE10, although these functions are defined immediately above the call to them, they are seen as not defined

The following function definition is immediately followed by an input field with a call to it, yet the function is not seen as defined?!
<script>
<![CDATA[
function SubmitCross()
{
var axis1 = "select_flavor" + document.all.item('axisflavor1').selectedIndex + "_axis1";
var axis2 = "select_flavor" + document.all.item('axisflavor2').selectedIndex + "_axis2";
var variable1 = document.all.item(axis1).value.split(".");
if (variable1[0].indexOf("error") == -1)
{
var questionY = variable1[0].split("-");
var implicitTypeY = variable1[1].split("-");
var flavorY = variable1[2].split("-");
document.all.item('question_y').value = questionY[1];
document.all.item('implicit_type_y').value = implicitTypeY[1];
document.all.item('flavor_y').value = flavorY[1];
document.all.item('choice_y').value = -1;
}
else
{
alert ("Please select a valid x-axis variable");
return;
}
var variable2 = document.all.item(axis2).value.split(".");
if (variable2[0].indexOf("error") == -1)
{
var questionX = variable2[0].split("-");
var implicitTypeX = variable2[1].split("-");
var flavorX = variable2[2].split("-");
document.all.item('question_x').value = questionX[1];
document.all.item('implicit_type_x').value = implicitTypeX[1];
document.all.item('flavor_x').value = flavorX[1];
document.all.item('choice_x').value = -1;
}
else
{
alert ("Please select a valid y-axis variable");
return;
}
]]>
This following input element contains a call to the above function, literally right below it. IE 10 does not want to recognize that it's a function?!?!
<input class="popuButton" type="button" value="Go!" onclick="SubmitCross();"/>    
I don't know what the "< ! [CDATA[" does for you. But my bet would be that your function has definition errors. Try debug your javascript. Seems you missed the closing '{' bracket?

Validating email addresses using jQuery and regex

I'm not too sure how to do this. I need to validate email addresses using regex with something like this:
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|edu|gov|mil|biz|info|mobi|name|aero|asia|jobs|museum)
Then I need to run this in a jQuery function like this:
$j("#fld_emailaddress").live('change',function() {
var emailaddress = $j("#fld_emailaddress").val();
// validation here?
if(emailaddress){}
// end validation
$j.ajax({
type: "POST",
url: "../ff-admin/ff-register/ff-user-check.php",
data: "fld_emailaddress="+ emailaddress,
success: function(msg)
{
if(msg == 'OK') {
$j("#fld_username").attr('disabled',false);
$j("#fld_password").attr('disabled',false);
$j("#cmd_register_submit").attr('disabled',false);
$j("#fld_emailaddress").removeClass('object_error'); // if necessary
$j("#fld_emailaddress").addClass("object_ok");
$j('#email_ac').html(' <img src="img/cool.png" align="absmiddle"> <font color="Green"> Your email <strong>'+ emailaddress+'</strong> is OK.</font> ');
} else {
$j("#fld_username").attr('disabled',true);
$j("#fld_password").attr('disabled',true);
$j("#cmd_register_submit").attr('disabled',true);
$j("#fld_emailaddress").removeClass('object_ok'); // if necessary
$j("#fld_emailaddress").addClass("object_error");
$j('#email_ac').html(msg);
}
}
});
});
Where does the validation go and what is the expression?
UPDATES
http://so.lucafilosofi.com/jquery-validate-e-mail-address-regex/
using new regex
added support for Address tags (+ sign)
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
}
if( !isValidEmailAddress( emailaddress ) ) { /* do stuff here */ }
NOTE: keep in mind that no 100% regex email check exists!
This is my solution:
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
// alert( pattern.test(emailAddress) );
return pattern.test(emailAddress);
};
Found that RegExp over here: http://mdskinner.com/code/email-regex-and-validation-jquery
$(document).ready(function() {
$('#emailid').focusout(function(){
$('#emailid').filter(function(){
var email = $('#emailid').val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if ( !emailReg.test( email ) ) {
alert('Please enter valid email');
} else {
alert('Thank you for your valid email');
}
});
});
});
Lolz this is much better
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/);
return pattern.test(emailAddress);
};
I would recommend that you use the jQuery plugin for Verimail.js.
Why?
IANA TLD validation
Syntax validation (according to RFC 822)
Spelling suggestion for the most common TLDs and email domains
Deny temporary email account domains such as mailinator.com
How?
Include verimail.jquery.js on your site and use the function:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
Javascript:
var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);
The regex is not allowed for:
abc#gmail..com
abc#gmail.com..
Allowed for:
abc.efg#gmail.com
abc#gmail.com.my
Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/
We can also use regular expression (/^([\w.-]+)#([\w-]+)((.(\w){2,3})+)$/i) to validate email address format is correct or not.
var emailRegex = new RegExp(/^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$/i);
var valid = emailRegex.test(emailAddress);
if (!valid) {
alert("Invalid e-mail address");
return false;
} else
return true;
Try this
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
return pattern.test(emailAddress);
};
you can use this function
var validateEmail = function (email) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
if (pattern.test(email)) {
return true;
}
else {
return false;
}
};
Native method:
$("#myform").validate({
// options...
});
$.validator.methods.email = function( value, element ) {
return this.optional( element ) || /[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}/.test( value );
}
Source: https://jqueryvalidation.org/jQuery.validator.methods/