codeigniter custom form validation wont work - regex

I have a input form and I want to check for some user_name properties. For instance if username is only lowercase with numbers. I am using callback function but given only a simple string such as "a" wont return true .. I really dont understand. What am I doing wrong ??
$this->form_validation->set_rules('user_name','User name','required|callback_validate_user_name');
...
if($this->form_validation->run() !== false){
$data['main_content'] = 'pages/news_page';
$this->load->view('templates/home_body_content', $data);
} else {
echo "Damn!";
}
function validate_user_name($user_name){
if(preg_match('/a/', $user_name) === true){
return true;
}
return false;
}

First, PHP preg_match() returns 1 if the pattern matches given subject [Reference]
So use === 1 or == TRUE instead of === true.
Second, callback function should return FALSE when /a/ pattern is occurred, and return TRUE if not.

Related

Getting ArgumentNullException on empty Entry

I am trying to validate a user typed email in Xamarin.Forms with Regex. For that I require that the pattern includes:
var emailPattern = #"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" +
#"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
Then I match the typed email with the pattern:
if (!Regex.IsMatch(Email, emailPattern) || Email == null)
{
EmailIsWrong = true;
}
else{
EmailIsWrong = false;
}
However, an error occurs, which is System.ArgumentNullException: Value cannot be null.
Parameter name: input on my if statement. I tried fixing it by having Email == null. This error occurs whenever I let the entry be empty.
For your problem, change the order of operands may help.
Like:
if (Email == null || !Regex.IsMatch(Email, emailPattern))
{
EmailIsWrong = true;
}
else{
EmailIsWrong = false;
}
If the first operand is satisfied, the second operand will be skipped

If condition with model in laravel

Regist Controller:
$check = Regist::whereMob($mob)->get();
if($check == emptyArray()){
return back()->with('status', 'input error!!');
}
Here i want to return back if $check gets no input.
It produces (E_ERROR)
Call to undefined function App\Http\Controllers\emptyArray()
How to check this.
This is one of the way to check empty
if ($check->isEmpty()) {...}
or
if (empty($check)) {...}

Array comparison?

I am making a function that takes in an example and an ip address. For ex.
compare('192.168.*','192.168.0.42');
The asterix indicates that the following parts of ip can be anything. The function returns true or false based on if the example and ip is a match. I tried this kind of solution.
var compare = function(example, ip){
var ex = example.split(".");
var ip = ip.split(".");
var t = 0;
for(var i=0; i<4; i++){
if(ex[i] == ip[i] || ex[i] == "*" || typeof ex[i] === 'undefined' && ex[i-1] == "*"){
t++
if(t==4){
return true
}
}else{
return false;
}
}
}
What are the main advantages of using regular expression over this solution? What would be the best regular expression to do this?
How about checking if they are not equal then just return false?
var compare = function(example, ip){
// You should have some basic IP validations here for both example and ip.
var ex = example.split(".");
var ip = ip.split(".");
for(var i=0; i<ex.length; i++){
if(ex[i]=='*')
break;
if(ex[i]!=ip[i])
return false;
}
return true;
}
alert(compare('333.321.*','333.321.345.765'));
alert(compare('333.322.*','333.321.345.765'));
alert(compare('333.321.345.*','333.321.345.765'));
This goes way better with regular expressions. Try this:
function compare(example, ip) {
var regexp = new RegExp('^' + example.replace(/\./g, '\\.').replace(/\*/g, '.*'));
return regexp.test(ip);
}
compare('192.168.*', '192.168.0.42'); // => true
compare('192.167.*', '192.168.0.42'); // => false
What this does is, it translates your pattern to an regular expression. Regular expressions are extremely powerful in matching string. It also covers cases like this:
compare('192.168.*.42', '192.168.1.42'); // => true
compare('192.167.*.42', '192.168.1.43'); // => false

java.lang.AssertionError: expected

My TestNG test implementation throws an error despite the expected value matches with the actual value.
Here is the TestNG code:
#Test(dataProvider = "valid")
public void setUserValidTest(int userId, String firstName, String lastName){
User newUser = new User();
newUser.setLastName(lastName);
newUser.setUserId(userId);
newUser.setFirstName(firstName);
userDAO.setUser(newUser);
Assert.assertEquals(userDAO.getUser().get(0), newUser);
}
The error is:
java.lang.AssertionError: expected [UserId=10, FirstName=Sam, LastName=Baxt] but found [UserId=10, FirstName=Sam, LastName=Baxt]
What have I done wrong here?
The reason is simple. Testng uses the equals method of the object to check if they're equal. So the best way to achieve the result you're looking for is to override the equals method of the user method like this.
public class User {
private String lastName;
private String firstName;
private String userId;
// -- other methods here
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!User.class.isAssignableFrom(obj.getClass())) {
return false;
}
final User other = (User) obj;
//If both lastnames are not equal return false
if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)) {
return false;
}
//If both lastnames are not equal return false
if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) {
return false;
}
//If both lastnames are not equal return false
if ((this.userId == null) ? (other.userId != null) : !this.userId.equals(other.userId)) {
return false;
}
return true;
}
}
and it'll work like magic
It seems you are either comparing the wrong (first) object or equals is not correctly implemented as it returns false.
The shown values are just string representations. It doesn't actually mean that both objects have to be equal.
You should check if userDAO.getUser().get(0) actually returns the user you are setting before.
Posting the implementation of User and the userDAO type might help for further clarification.
NOTE: Note directly related to this question but it's answer to my issue that got me to this question. I am sure more ppl might end-up on this post looking for this solution.
This is not precisely the a solution if Equals method needs overriding but something that I very commonly find myself blocked due to:
If you have used Capture and are asserting equality over captured value, please be sure to get the captured value form captured instance.
eg:
Capture<Request> capturedRequest = new Capture<>();
this.testableObj.makeRequest(EasyMock.capture(capturedRequest))
Assert.assertEquals(capturedRequest.getValue(), expectedRequest);
V/S
Assert.assertEquals(capturedRequest, expectedRequest);
while the compiler wont complain in either case, the Assertion Obviously fails in 2nd case

How to check whether given email address is invalid in action script 3?

I need to check whether given email address is invalid in action script. Following is the code/regex i came up with.
private function isEmailInvalid(email:String):Boolean
{
var pattern:RegExp = /(\w|[_.\-])+#((\w|-)+\.)+\w{2,4}+/;
var result:Object = pattern.exec(email);
if(result == null) {
return true;
}
return false;
}
But it seems like above code do not cover all the test cases in the following link:
http://blogs.msdn.com/b/testing123/archive/2009/02/05/email-address-test-cases.aspx
Does anyone have better way of doing this?
Folowing are the tested valid emails i used (above function should return "false" for these):
firstname.lastname#domain.com
firstname+lastname#domain.com
email#domain.co.jp
Folowing are the invalid ones (so function should return "true" for these):
email#domain#domain.com
.email#domain.com
email..email#domain.com
plainaddress, email#domain..com
Remove the + at the last and you must need to put anchors.
^(\w|[_.\-])+#((\w|-)+\.)+\w{2,4}$
Simplified one,
^[\w_.-]+#([\w-]+\.)+\w{2,4}$
DEMO
Try this RegExp :
RegExp = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;