Youtube URL validation ios - ios

I am using this method to validate youtube url but it's not working.
-(BOOL) validateUrl: (NSString *) candidate
{
NSString *urlRegEx = #"(http://youtu.be/[a-zA-Z0-9_-]+)";
urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
-(BOOL) validateUrl1: (NSString *) candidate1
{
NSString *urlRegEx1 = #"(https://(www|m){0,1}.youtube.com/(watch|playlist)[?]v=[a-zA-Z0-9_-]+)";
urlTest1 = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx1];
return [urlTest1 evaluateWithObject:candidate1];
}
Even if I edit the url and make it y.be instead of youtu.be, still
these methods are returning YES
. Kindly tell me what's wrong in my code.
If any one has a better RegEx please share that with me.
I would also like to know how to write a RegEx.

If you want to check if String is the link to the youtube video (not the link for channel, or for embedding video):
func isYoutubeLink(checkString checkString: String) -> Bool {
let youtubeRegex = "(http(s)?:\\/\\/)?(www\\.|m\\.)?youtu(be\\.com|\\.be)(\\/watch\\?([&=a-z]{0,})(v=[\\d\\w]{1,}).+|\\/[\\d\\w]{1,})"
let youtubeCheckResult = NSPredicate(format: "SELF MATCHES %#", youtubeRegex)
return youtubeCheckResult.evaluateWithObject(checkString)
}

NSString *urlString = [NSString stringWithFormat:#"URL_STRING"];
NSString *urlRegEx = #"(?:(?:\.be\/|embed\/|v\/|\\?v=|\&v=|\/videos\/)|(?:[\\w+]+#\\w\/\\w(?:\/[\\w]+)?\/\\w\/))([\\w-_]+)";
NSPredicate *urlPredic = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
BOOL isValidURL = [urlPredic evaluateWithObject:urlString];
if(isValidURL)
{
// your URL is valid;
}
else
{
// show alert message for invalid URL;
}
now please check let me know i'm waiting your replay it's work or not.

If it is regex that you are looking for, then perhaps you could try this:
(((?:https?:\/\/)?(?:www\.|m\.)?(?:youtube\.[a-z]{2,}|youtu\.be)(?:\/(?:playlist|watch\?|channel\/|user\/)[\w=]+)+)
It will match:
http://, https:// or none of these
www. or m. or none of these
youtube.<anyTLD> or youtu.be
/
playlist, watch?, channel or user
a string of characters from a-zA-Z0-9 and = more than 1 time
This should effectively match most urls on Youtube apart from the homepage, which if requested I could add in with a bit of tweaking.
You may have to add another escape, I haven't got much experience with objective-c
(((?:https?:\\/\\/)?(?:www\\.|m\.)?(?:youtube\\.[a-z]{2,}|youtu\\.be)(?:\\/(?:playlist|watch\\?|channel\\/|user\\/)[\\w=]+)+)
Here is an example of it working in Javascript, Python and PCRE:
https://regex101.com/r/sG1xP7/1
I hope this helps you

For Swift 5:
func isValidYouTubeLink(givenString: String) -> Bool {
let youtubeRegex = "(http(s)?:\\/\\/)?(www\\.|m\\.)?youtu(be\\.com|\\.be)(\\/watch\\?([&=a-z]{0,})(v=[\\d\\w]{1,}).+|\\/[\\d\\w]{1,})"
let youtubeCheckResult = NSPredicate(format: "SELF MATCHES %#", youtubeRegex)
return youtubeCheckResult.evaluate(with: givenString)
}

Related

How to get Values from a NSString

I have an NSString. It is a URL I am getting when using Universal Links. I want to get id value from it. Is there any direct methods in SDK or do we need to use componententsSeparated String values?
Below is the NSString/URL:
https://some.com/cc/test.html?id=3039#value=test
I want to get two things: "test" from test.html and "id" value.
Use NSURLComponents created from an NSURL or NSString of your URL.
From there you can use path to get the /cc/test.html part. Then use lastPathComponent to get test.html and finally use stringByDeletingPathExtension to get test.
To get the "id" value start with the components' queryItems value. Iterate that array finding the NSURLQueryItem with the name of "id" and then get its value.
You could create NSURLComponents from URL string get parameters by calling queryItems method. It will return array of NSURLQueryItem
NSURLComponents *components = [NSURLComponents componentsWithString:#"https://some.com/cc/test.html?id=3039&value=test"];
NSArray *array = [components queryItems];
for(NSURLQueryItem *item in array){
NSLog(#"Name: %#, Value: %#", item.name, item.value);
}
NSLog(#"Items: %#", array);
We can make extension
extension URL {
func getParamValue(paramaterName: String) -> String? {
guard let url = URLComponents(string:self.absoluteString ) else { return nil }
return url.queryItems?.first(where: { $0.name == paramaterName})?.value
}
}
Now you can call like below
let someURL = URL(string: "https://some.com/cc/test.html?id=3039&value=test")!
someURL.getParamValue("id") // 3039
someURL.getParamValue("value") // test

A clean and robust way to parse URL strings in Objective C

I have a requirement to take a string that represents a URL that can be in many formats and standardise it so it conforms with the URL spec.
If the URL string does not have a scheme, or it has a scheme that is not 'http' or 'https', it should use a default scheme.
I wanted to use NSURLComponents but if a scheme is not provided it parses the host as a path
NSURLComponents *components = [NSURLComponents componentsWithString:#"www.google.com.au"];
components.scheme = #"http";
NSLog(#"1: %#", components.path);
NSLog(#"2: %#", components.host);
NSLog(#"3: %#", components.string);
testtest[2619:869020] 1: www.google.com.au
testtest[2619:869020] 2: ((null))
testtest[2619:869020] 3: http:www.google.com.au <-- Invalid
Therefore I ended up with this category on NSString
#define DEFAULT_SCHEME #"http"
#implementation NSString (standardiseUrlFormat)
- (NSString*)standardiseUrlFormat {
NSURLComponents *components = [NSURLComponents componentsWithString:self];
BOOL hasScheme = components.scheme != nil;
// If no scheme or an invalid scheme is provided, default to http
if (!hasScheme) {
// We have to use string concatenation here because NSURLComponents will
// put the hostname as the path if there is no scheme
return [NSString stringWithFormat:#"%#://%#", DEFAULT_SCHEME, self];
}
// Now we know that a scheme exists, check if it is a correct scheme
if (![components.scheme isEqualToString:#"http"] &&
![components.scheme isEqualToString:#"https"]) {
// Overwrite scheme if not supported
components.scheme = DEFAULT_SCHEME;
}
return [components string];
}
#end
With the following output
NSLog(#"1: %#", [#"http://www.google.com" standardiseUrlFormat]);
NSLog(#"2: %#", [#"www.google.com" standardiseUrlFormat]);
NSLog(#"3: %#", [#"https://www.google.com" standardiseUrlFormat]);
NSLog(#"4: %#", [#"https://www.google.com/some_path" standardiseUrlFormat]);
NSLog(#"5: %#", [#"www.google.com/some_path" standardiseUrlFormat]);
testtest[7411:944022] 1: http://www.google.com
testtest[7411:944022] 2: http://www.google.com
testtest[7411:944022] 3: https://www.google.com
testtest[7411:944022] 4: https://www.google.com/some_path
testtest[7411:944022] 5: http://www.google.com/some_path
Can anyone suggest a cleaner solution that doesn't use two methods (NSURLComponents and string concatenation) to construct the string?
Don't use string concatenation at all. Use NSURLComponents to form the desired NSURL; that's what it's for. For example, if you don't like what the scheme is, set the scheme to what you do want.
EDIT I guess I was thinking that having detected that this is a hostless URL you would rejigger it by hand, e.g.
let s = "www.apple.com/whatever" as NSString
let arr = s.pathComponents
let c = NSURLComponents()
c.scheme = "http"
c.host = arr[0]
c.path = "/" + (Array(arr.dropFirst()) as NSArray).componentsJoinedByString("/")
But perhaps this can't be done, and the problem really is that a URL without a scheme is more or less not a URL.

Validate string with various validation in iOS

I've been facing some issue with to valid string with following condition. The respective conditions are as follows:
String should contain MAX length(which is 7) and should not less Than 6
First character must be from A-Z (should consider aUppercase only)
remaining character must contain only digit (0 to 9).
Here is an example of String I want to valid A12342 (desire output with validation)
Thanks in advance ,Any help will be appreciated.If any one need more information about my query please let me know .
-(BOOL)CheckConditionForValidation
{ if([textfield.text isequalToString:#""]){
return FALSE
}
//else if (//validation for my specific number)
//{
//want to implement logic here
//}
}
Try this rejex pattern [A-Z][0-9]{5,6}
check it online with the link Online rejex check
and if it work than use like this
- (BOOL)checkValidation:(UITextField *)textField
{
NSString *rejex = #"<your pattern>";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", rejex];
//if rejex fullfil than it will return true else false.
return [emailTest evaluateWithObject:textField.text];
}

Regex Repeatead Consecutive Characters IOS

I'm trying to valide an iOS textfield with a regex for no repeated consecutive characteres
eg. txt12344 -> should fail
this is my code
NSString *regexConsecutive = #"(.)\1{1,}";
NSPredicate *passConsecutivePredicate = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", regexConsecutive];
if ([passConsecutivePredicate evaluateWithObject:self.txtPassword.text]){
errorMessage = #"No repeated consecutive characters allowed !";
}
but I'm not sure if self matches it's the right way to achieve this.
Thanks a lot !

NSPredicate to match unescaped apostrophes

I'd like to check an NSString (json) if there are any unescaped apostrophes, but the NSPredicate won't find it, even if the regex is correct.
Here's my code:
NSString* regx = #"[^\\\\]'";
NSPredicate* p = [NSPredicate predicateWithFormat:#"SELF MATCHES %#",regx];
if([p evaluateWithObject:json]){
//gotit
...
I know that there are some apostrophes that are not escaped, but NSPredicate just doesn't find it.
Any idea how to solve this problem?
Also if I look at the json I see the apostrophes as \u0027.
"SELF MATCHES …" tries to match the entire string, therefore you have to use the regex
NSString* regx = #".*[^\\\\]'.*";
Alternatively:
NSString* regx = #"[^\\\\]'";
NSRange r = [json rangeOfString:regx options:NSRegularExpressionSearch];
if (r.location != NSNotfound) {
…
}
But the question remains why this is necessary. NSJSONSerialization should handle
all escaping and quoting correctly.
This is the regex which works for me:
.*[^\\\\]\\\\u0027.*

Resources